export default {
  namespaced: true,
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
  }),
  mutations: {
    saveToStorage(state) {
      // console.log(state.cart);
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },

    toggleCheck(state, goodsId) {
      const goods = state.cart.find(item => item.goods_id === goodsId)
      goods.goods_state = !goods.goods_state
      // 重新持久化保存到本地
      this.commit('m_cart/saveToStorage');
    },
    toggleAllCheck(state, flag) {
      state.cart.forEach(item => {
        item.goods_state = flag
      })
    },
    changeCount(state, {
      goodsId,
      goodsNum
    }) {
      // console.log("in cart:", goodsId, goodsNum);
      const goods = state.cart.find(item => item.goods_id === goodsId)
      // console.log(goods);
      goods.goods_count = goodsNum
      this.commit('m_cart/saveToStorage');
    },
    // 滑动删除商品
    removeGoodsItemById(state,goodsId){
      state.cart = state.cart.filter(item=>item.goods_id!==goodsId)
      this.commit('m_cart/saveToStorage');
      
    }
    
  },
  actions: {
    addToCart({
      commit,
      state
    }, goods) {
      const result = state.cart.find(item => item.goods_id === goods.goods_id)
      if (!result) {
        state.cart.push(goods)
      } else {
        result.goods_count += goods.goods_count;
      }
      commit('saveToStorage')
    }
  },
  getters: {
    total(state) {
      let sum = 0
      // 循环统计商品的数量，累加到变量 c 中
      state.cart.forEach(goods => sum += goods.goods_count)
      return sum
    },
    // 购物车商品总数
    getCartTotal(state) {
      return state.cart.reduce((pre, item) => pre + item.goods_count, 0)
    },
    // 选中的商品项
    getCheckedCart(state) {
      return state.cart.filter(item => item.goods_state)
    },
    // 选中的总数
    getCheckedCount(state, getters) {
      return getters.getCheckedCart.reduce((pre, item) => pre + item.goods_count, 0)
    },
    // 选中的总价
    getCheckedPrice(state, getters) {
      return getters.getCheckedCart.reduce((pre, item) => pre + item.goods_count * item.goods_price, 0).toFixed(
        2)
    },
    // 是否全选
    isAllChecked(state) {
      return state.cart.every(item => {
        return item.goods_state
      })
    }
  },
}